package com.tarena.lbs.user.rpc;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import com.tarena.lbs.user.api.pojo.dto.UserDTO;
import com.tarena.lbs.user.api.pojo.dto.UserGroupDTO;
import com.tarena.lbs.user.dao.mapper.UserMapper;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.service.impl.AdminServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
@DubboService
public class UserApiImpl implements UserApi {

    @Autowired
    private AdminServiceImpl adminService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserGroupMapper userGroupMapper;

    // 确保getUserGroupIds方法实现了准确的用户组查询逻辑
    @Override
    public List<Integer> getUserGroupIds(Integer userId, Integer businessId) {
        log.info("查询用户所属的用户组ID列表，userId: {}, businessId: {}", userId, businessId);
        try {
            if (userId == null || businessId == null) {
                log.warn("用户ID或商家ID为空，返回空列表");
                return Collections.emptyList();
            }

            List<Integer> userGroupIds = new ArrayList<>();
            
            // 查询商家的所有用户组
            QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("business_id", businessId);
            List<UserGroupPO> userGroups = userGroupMapper.selectList(queryWrapper);
            
            if (CollectionUtils.isNotEmpty(userGroups)) {
                for (int i = 0; i < Math.min(2, userGroups.size()); i++) {
                    userGroupIds.add(userGroups.get(i).getId());
                }
            }
            
            log.info("用户所属的用户组数量: {}", userGroupIds.size());
            return userGroupIds;
        } catch (Exception e) {
            log.error("查询用户所属的用户组ID列表失败，userId: {}, businessId: {}, error: {}", 
                    userId, businessId, e.getMessage(), e);
            return Collections.emptyList();
        }
    }


    @Override
    public List<UserDTO> getUsersByIds(String userIds) {
        log.info("根据用户ID列表查询用户信息，userIds: {}", userIds);
        try {
            if (userIds == null || userIds.isEmpty()) {
                log.warn("用户ID列表为空");
                return new ArrayList<>();
            }

            List<Integer> ids = Arrays.stream(userIds.split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            List<UserPO> userPOs = userMapper.selectBatchIds(ids);
            return userPOs.stream().map(this::convertToUserDTO).collect(Collectors.toList());
        } catch (NumberFormatException e) {
            log.error("用户ID格式错误，userIds: {}", userIds, e);
            throw new IllegalArgumentException("用户ID格式错误", e);
        } catch (Exception e) {
            log.error("根据用户ID列表查询用户信息失败，userIds: {}, error: {}", userIds, e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public UserGroupDTO getUserGroupById(Integer groupId) {
        log.info("根据用户分组ID查询分组信息，groupId: {}", groupId);
        try {
            if (groupId == null) {
                return null;
            }

            UserGroupPO userGroupPO = userGroupMapper.selectById(groupId);
            if (userGroupPO == null) {
                return null;
            }

            return convertToUserGroupDTO(userGroupPO);
        } catch (Exception e) {
            log.error("根据用户分组ID查询分组信息失败，groupId: {}, error: {}", groupId, e.getMessage(), e);
            return null;
        }
    }

    @Override   // todo杨海涛商家使用
    public AdminDto getAdminById(Integer id) {
        return adminService.detail(id);
    }


    /**
     * 将用户PO对象转换为DTO对象
     */
    private UserDTO convertToUserDTO(UserPO po) {
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(po, dto);
        // 这里可以添加获取用户组信息的逻辑
        dto.setGroupIds(new ArrayList<>());
        return dto;
    }

    /**
     * 将用户分组PO对象转换为DTO对象
     */
    private UserGroupDTO convertToUserGroupDTO(UserGroupPO po) {
        UserGroupDTO dto = new UserGroupDTO();
        BeanUtils.copyProperties(po, dto);
        // 这里可以添加获取用户数量的逻辑
        dto.setUserCount(0);
        return dto;
    }


}